class h_sys {

	async sendTemplateMsg(msgData) {
		const {app, template, wxUserId, page = '/pages/index/index', formId, data, color, bigWord} = msgData
		if(!/^\w+$/.test(formId)) {
			console.error(`form id ${formId} invalid, send template failed`)
			this.common.writeLog('error', `form id ${formId} invalid, send template failed`)
			return
		}
		if(!this.config.miniApp[app] || !this.config.miniApp[app].msgTemplate[template])
			return this.reject('-2039', 'wx template msg id not found')
		const {accessToken} = await this.common.getAccessToken('gtClient')
		let dataObj = {}
		for(let i = 0;i < data.length;i++) {
			let msg = data[i].split('|')
			if(msg.length == 0)
				return this.reject('-2040', 'wx template msg data invalid')
			dataObj[`keyword${i + 1}`] = {
				value: msg[0],
				color: msg[1] || '#333'
			}
		}
		console.log(dataObj)
		const {errcode, errmsg} = await this.common.reqPost({
			url: 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send',
			getData: {
				access_token: accessToken
			},
			data: {
				touser: wxUserId,
				template_id: this.config.miniApp[app].msgTemplate[template],
				page,
				form_id: formId,
				data: dataObj,
				color,
				emphasis_keyword: bigWord ? `keyword${bigWord}.DATA` : undefined
			},
			json: true
		})
		if(errcode != 0) {
			console.error(errcode, errmsg)
			return this.reject('-2041', `send wx tamplate msg failed ${errcode} ${errmsg}`)
		}
	}

	async makeGtCode(_interface = 'B', count = 1) {
		if(['A', 'B', 'C'].indexOf(_interface) == -1)
			return this.reject('-2066', 'make code interface invalid')
		if(this.common.checkJobRun('makeGtCodeService'))
			return this.reject('-2062', 'make code service status is running')
		const {page, width, auto_color, line_color, everyTimeMakeCount, makeMaxCount, tableCountFull, makeInterval, makeTaskExpire} = this.config.gtCode
		if(count > (makeMaxCount || 100))
			return this.reject('-2063', 'make code count too many')
		let tableIndexList = []
		for(let i = 0;i < count;i++) {
			const codeId = await this.common.createRandomStr(32)
			const tableIndex = this.common.hashTableIndex(codeId)
			if(!tableCountFull && tableIndexList.indexOf(tableIndex) == -1) {
				await this.mysql.code.createTable(`map_${tableIndex}`, [
					"`Id` int(11) NOT NULL AUTO_INCREMENT",
					"`codeId` varchar(32) COLLATE utf8mb4_bin NOT NULL DEFAULT '' COMMENT '二维码ID'",
					"`storeId` varchar(10) COLLATE utf8mb4_bin NOT NULL DEFAULT '' COMMENT '商户ID'",
					"`tableNum` varchar(10) COLLATE utf8mb4_bin NOT NULL DEFAULT '' COMMENT '桌号'",
					"`codeFreeze` tinyint(1) NOT NULL DEFAULT '0' COMMENT '桌码是否冻结'",
					"PRIMARY KEY (`Id`)",
					"UNIQUE KEY `codeId` (`codeId`)"
				], {
					autoId: true,
					comment: `粿团二维码映射表${tableIndex}`
				})
				tableIndexList.push(tableIndex)
			}
			await this.redis.gtCode.set(codeId, this.common.timestamp(), makeTaskExpire || 86400)
		}
		this.common.createJob('makeGtCodeService', `*/${makeInterval || 5} * * * * *`, {
			function: async () => {
				const codeIds = await this.redis.gtCode.scan('*', everyTimeMakeCount || 10)
				if(codeIds.length == 0) {
					this.common.stopJob('makeGtCodeService')
					return
				}
				const {accessToken} = await this.common.getAccessToken('gtClient')
				console.log(codeIds)
				for(let codeId of codeIds) {
					console.log(codeId)
					await this.redis.gtCode.delete(codeId)
					const {contentType, contentLen, data} = await this.common.reqPost({
						url: ({
							A: `https://api.weixin.qq.com/wxa/getwxacode?access_token=${accessToken}`,
							B: `https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=${accessToken}`,
							C: `https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=${accessToken}`
						}[_interface || 'B']),
						data: ({
							A: {
								path: `${page}?codeId=${codeId}`,
								width,
								auto_color,
								line_color
							},
							B: {
								scene: codeId,
								page,
								width,
								auto_color,
								line_color
							},
							C: {
								path: `${page}?codeId=${codeId}`,
								width
							}
						}[_interface || 'B']),
						getContentInfo: true,
						getBuffer: true
					})
					if(data.errmsg) {
						const {errcode, errmsg} = data
						console.error('make gt code failed', errcode, errmsg)
						this.common.writeLog('error', `make gt code failed ${errcode} ${errmsg}`)
						return
					}
					await this.fs.outputFile(`${this.config.server.gtCodePath}/${codeId}.jpg`, data).catch(err => {
						console.error('write gt code file failed', err)
						this.common.writeLog('error', `write gt code file failed`, false, err)
					})
					const result = await this.mysql.code.insert(`map_${this.common.hashTableIndex(codeId)}`, 'codeId', [codeId]).catch(err => {
						console.error('insert gt code error', err)
						this.common.writeLog('error', `insert gt code error`, false, err)
					})
					if(result == 0) {
						console.error('insert gt code failed')
						this.common.writeLog('error', `insert gt code failed`)
					}
				}
			}
		}, {
			function: async () => {
				console.log('make gt code done')
				this.common.writeLog('info', 'make gt code done')
			}
		},  err => {
			console.error('make gt code failed', err)
			this.common.writeLog('error', `make gt code failed`, false, err)
		}, true)
	}

	async stopMakeGtCodeService() {
		await this.common.stopJob('makeGtCodeService')
	}

}

module.exports = h_sys